<template>
	<view class="page" :data-theme="theme">
		<view class="system-height" :style="{height:statusBarHeight}"></view>
		<!-- #ifdef MP -->
		<view class="title-bar" style="height: 43px;">
			<view class="icon" @click="back" v-if="!isHome">
				<image src="../static/left.png"></image>
			</view>
			<view class="icon" @click="home" v-else>
				<image src="../static/home.png"></image>
			</view>
			账户登录
		</view>
		<!-- #endif -->
		<view class="wechat_login">
			<view class="img">
				<image src="../static/images/wechat_login.png" mode="widthFix"></image>
			</view>
			<view class="acea-row row-between btn-wrapper">
				<!-- #ifdef H5 -->
				<button hover-class="none" @click="wechatLogin" class="bg-green btn1">微信登录</button>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<button hover-class="none" @click="getUserProfile" data-eventsync="true" class="bg-green btn1">手机号快捷登录</button>
				<!-- <button hover-class="none" @click="waitLogin" class="bg-red btn1">稍后登录</button> -->
				<button hover-class="none" @click="toUP" class="bg-red btn1">账号密码登录</button>
				<!-- #endif -->
				<!-- #ifdef MP-TOUTIAO -->
				<!-- <button hover-class="none" @click="getUserProfile" data-eventsync="true" class="bg-green btn1">手机号快捷登录</button> -->
				<!-- <button hover-class="none" @click="waitLogin" class="bg-red btn1">稍后登录</button> -->
				<button hover-class="none" @click="toUP" class="bg-red btn1">账号密码登录</button>
				<!-- #endif -->
			</view>
		</view>
		<block v-if="isUp">
			<mobileLogin :isUp="isUp" @close="maskClose" :authKey="authKey" @wechatPhone="wechatPhone"></mobileLogin>
		</block>
		<atModel v-if="isPhoneBox" 
		:userPhoneType="true" 
		:isPhoneBox="isPhoneBox"  
		:authKey="authKey" 
		:content="getPhoneContent"
		 @closeModel="bindPhoneClose" 
		 @confirmModel="confirmModel"></atModel>
	</view>
</template>

<script>
	const app = getApp();
	let statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
	import mobileLogin from '../components/login_mobile/index.vue'
	import atModel from '../components/accredit/index.vue'
	import {mapGetters} from "vuex";
	import {getLogo,getUserPhone} from '@/api/public';
	import {
		LOGO_URL,
		EXPIRES_TIME,
		USER_INFO,
		STATE_R_KEY
	} from '@/config/cache';
	import {
		HTTP_REQUEST_URL
	} from '@/config/app';
	import {
		spread,
		getIm
	} from '@/api/user.js'
	let WebIM = require("@/pages/chatroom/utils/WebIM")["default"];
	import Routine from '@/libs/routine';
	import wechat from "@/libs/wechat";
	export default {
		data() {
			return {
				isUp: false,
				phone: '',
				statusBarHeight: statusBarHeight,
				isHome: false,
				isPhoneBox: false,
				logoUrl: '',
				code: '',
				authKey: '',
				options: '',
				userInfo: {},
				codeNum: 0,
				theme:app.globalData.theme,
				getPhoneContent:'申请获取您的手机号用于注册，完成后可使用商城更多功能'
			}
		},
		components: {
			mobileLogin,
			atModel
		},
		onLoad(options) {
			getLogo().then(res => {
				this.logoUrl = res.data.logoUrl
			})
			let that = this
			// #ifdef H5
			document.body.addEventListener("focusout", () => {
				setTimeout(() => {
					const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop ||
						0;
					window.scrollTo(0, Math.max(scrollHeight - 1, 0));
				}, 100);
			});
			const {
				code,
				state,
				scope
			} = options;
			this.options = options
			// 获取确认授权code
			this.code = code || ''
			//if(!code) location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
			if (code && this.options.scope !== 'snsapi_base') {
				let spread = app.globalData.spread ? app.globalData.spread : 0;
				//公众号授权登录回调 wechatAuth(code, Cache.get("spread"), loginType)
				wechat.auth(code, spread).then(res => {
					console.log(res)
					if (res.type === 'register') {
						this.authKey = res.key;
						this.isUp = true
					}
					if (res.type === 'login') {
						this.$store.commit('LOGIN', {
							token: res.token
						});
						this.$store.commit("SETUID", res.id);
						this.getUserInfo();
						
						//this.wechatPhone();
						//location.replace(decodeURIComponent(decodeURIComponent(option.query.back_url)));
					}
					
				}).catch(error => {});
			}
			// #endif
			let pages = getCurrentPages();
			// let prePage = pages[pages.length - 2];
			// if (prePage.route == 'pages/order_addcart/order_addcart') {
			// 	this.isHome = true
			// } else {
			// 	this.isHome = false
			// }

		},
		onUnload() {
			console.log("onUnload");
			this.$store.commit("SETLOGINSTATUS", false);
		},
		onHide() {
		console.log("hide")
			this.$store.commit("SETLOGINSTATUS", false);
		},
		methods: {
			back() {
				uni.navigateBack();
			},
			waitLogin(){
				this.back();
			},
			toUP(){
				uni.redirectTo({
					url: '/pages/users/login/index'
				})
			},
			home() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			modelCancel(){
				this.isPhoneBox = false;
			},
			// 弹窗关闭
			maskClose() {
				// this.isUp = false  //点击模态框会关闭登录弹框，防止用户误触而关闭
			},
			bindPhoneClose(data) {
				if (data.isStatus) {
					this.isPhoneBox = false
					this.$util.Tips({
						title: '登录成功',
						icon: 'success'
					}, {
						tab: 3
					})
				} else {
					this.isPhoneBox = false
				}

			},
			// #ifdef MP
			/**
			 * 登录成功之后回调
			 */
			getUserInfo() {
				this.$util.Tips({
					title: '登录成功',
					icon: 'success'
				}, {
					tab: 3
				})
			},
			getUserProfile() {
				let self = this;
				uni.showLoading({
					title: '正在登录中'
				});
				uni.getUserProfile({
					desc:'测试',
					success(res){
						console.log('res',res.userInfo)
					},fail(e){
						console.log("cuowu",e)
					}
				})
				console.log('login_spread',app.globalData.spread)
				Routine.getProvider().then(res=>{
					
					if(res[0] == 'weixin'){
						self.toWxMeth()
					}else if(res[0] == 'toutiao'){
						// uni.getUserProfile({
						// 	desc:'测试',
						// 	success(res){
						// 		console.log('res')
						// 	},fail(e){
						// 		console.log("cuowu",e)
						// 	}
						// })
					}
				})
				
			},
			toWxMeth(){
				let self = this;
				const hostSDKVersion = uni.getSystemInfoSync().hostSDKVersion; //小程序基础库版本号
				if (Routine.compareVersion(hostSDKVersion, '2.21.2') >= 0) {
					Routine.getCode()
						.then(code => {
							let userInfo = {
								code : code,
								spreadPid : app.globalData.spread, //获取推广人ID
								types: app.globalData.spreadType,
								infoId: app.globalData.infoId,
								storeCategory: app.globalData.storeCategory,
								type : 'routine'
							};
							self.getWxUser(userInfo);
						})
						.catch(res => {
							uni.hideLoading();
						});
				} else {
					Routine.getUserProfile().then(res => {
							Routine.getCode()
								.then(code => {
									let userInfo = {
										code : code,
										spreadPid : app.globalData.spread, //获取推广人ID
										types: app.globalData.spreadType,
										storeCategory: app.globalData.storeCategory,
										type : 'routine'
									};
									self.getWxUser(userInfo);
								})
								.catch(res => {
									uni.hideLoading();
								});
						})
						.catch(res => {
							uni.hideLoading();
						});
				}
			},
			toToutiao(){
				uni.getUserProfile({
					desc:'测试',
					success(res){
						console.log('res',res)
					},fail(e){
						console.log("cuowu",e)
					}
				})
				// Routine.getCode()
				// 	.then(code => {
				// 		console.log("头条 code",code)
				// 		let userInfo = {
				// 			code : code,
				// 			spreadPid : app.globalData.spread, //获取推广人ID
				// 			types: app.globalData.spreadType,
				// 			type : 'routineTt'
				// 		};
				// 		self.getWxUser(userInfo);
				// 	})
				// 	.catch(res => {
				// 		uni.hideLoading();
				// 	});
			},
			async toImLogin() {
				getIm().then(result=>{
					console.log('result',result)
					WebIM.conn.open({
						appKey: WebIM.config.appkey,
						user: result.data.username,
						pwd: '123456',
						success: function(res) {
							var imToken = res.access_token
							uni.setStorage({
								key: "imToken",
								data: imToken
							});
							uni.setStorage({
								key: "myUsername",
								data:  res.user.username
							});
						},
						error: function(r) {
							console.log("r",r)
						}
					});
				})
			},
			getWxUser(userInfo) {
				let self = this;
				Routine.authUserInfo(userInfo)
					.then(res => {
						console.log("userInfo",res)
						self.authKey = res.data.key;
						if (res.data.type === 'register') {
							uni.hideLoading();
							self.isPhoneBox = true
						}
						if (res.data.type === 'login') {
							uni.hideLoading();
							self.getUserInfo();
							getApp().globalData.getCurrentUser((data)=>{
								uni.setStorageSync('curUserInfo', JSON.stringify(data));
							})
							if(app.globalData.spread){
								spread(app.globalData.spread).then(res => {}) //登录成功后读取spread绑定分销关系
							}
							// 登录im
							this.toImLogin();
						}
					})
					.catch(res => {
						uni.hideLoading();
						uni.showToast({
							title: res,
							icon: 'none',
							duration: 2000
						});
					});
			},
			// #endif
			// #ifdef H5
			// 获取url后面的参数
			getQueryString(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
				var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
				var r = window.location.search.substr(1).match(reg);
				var q = window.location.pathname.substr(1).match(reg_rewrite);
				if (r != null) {
					return unescape(r[2]);
				} else if (q != null) {
					return unescape(q[2]);
				} else {
					return null;
				}
			},
			// 公众号登录
			wechatLogin() {
				if (!this.code && this.options.scope !== 'snsapi_base') {
					this.$wechat.oAuth('snsapi_userinfo', '/pages/users/wechat_login/index');
				} else {
					// if (this.authKey) {
					// 	this.isUp = true;
					// }
					this.isUp = true;
				}
			},
			// 输入手机号后的回调
			wechatPhone() {
				this.$Cache.clear('snsapiKey');
				if (this.options.back_url) {
					let url = uni.getStorageSync('snRouter');
					url = url.indexOf('/pages/index/index') != -1 ? '/' : url;
					if (url.indexOf('/pages/users/wechat_login/index') !== -1) {
						url = '/';
					}
					if (!url) {
						url = '/pages/index/index';
					}
					this.isUp = false
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					})
					setTimeout(res => {
						location.href = url
					}, 800)
				} else {
					uni.navigateBack()
				}
			}
			// #endif
		}
	}
</script>

<style lang="scss">
	page {
		background: #fff;
		height: 100%;
	}
    
	.page {
		background: #fff;
		height: 100%;
	}

	.wechat_login {
		padding: 72rpx 34rpx;

		.img image {
			width: 100%;
		}

		.btn-wrapper {
			margin-top: 86rpx;
			padding: 0 66rpx;

			button {
				width: 100%;
				height: 86rpx;
				line-height: 86rpx;
				margin-bottom: 40rpx;
				border-radius: 120rpx;
				font-size: 30rpx;

				&.btn1 {
					color: #fff;
				}

				&.btn2 {
					color: #666666;
					border: 1px solid #666666;
				}
			}
		}
	}

	.title-bar {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
	}

	.icon {
		position: absolute;
		left: 30rpx;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 86rpx;
		height: 86rpx;

		image {
			width: 50rpx;
			height: 50rpx;
		}
	}
</style>
